from xml.dom.minidom import Element
from Utils import *
from Log import *
import Event



class chat :
    def __init__(self, room) :
        self.Room = room
        self.Room.events.addListener("adduser" ,self.userIn) 
        self.Room.events.addListener("removeuser" ,self.userOut) 
        self.events = Event.EventDispatcher(self)
        dbg("chat loaded")
        
    def userIn(self, evt) :
        u = evt.args['user']
        u.events.addListener( "xml.chat" ,self.userChat)
        dbg("user come")
        
    def userOut(self, evt) :
        u = evt.args['user']
        u.events.removeListener( "xml.chat" ,self.userChat)
        dbg("user gone")
        
    def userChat(self, evt):
        u = evt.owner
        xmlNode = evt.args["xmlNode"]
        
        xmlNode.setAttribute('from', u.getUsername())
        to = xmlNode.getAttribute('to')
        
        resp = newxml(  )
        resp.firstChild.appendChild( xmlNode.cloneNode( True ) )
            
        evt = Event.Event( {'xmlDoc' : resp} )
        self.events.dispatch("chat", evt )
        
        if not evt.cancel : # if listener not cancel 
            if to in [ None , "" ] :
                self.Room.msgToAll( resp , [])
            else :
                self.Room.msgTo( to , resp )
                
